<html>
<head>
<script type="text/javascript" src="../../src/gew.js"></script>
<script type="text/javascript" src="cube.js"></script>
<!-- shaders -->
<script id="shader-vs" type="x-shader/x-vertex">
attribute vec3 aVertex;
attribute vec3 aNormal;
attribute vec2 aTexCoord0;

uniform mat4 uPMatrix;
uniform mat4 uMVMatrix;
uniform vec4 uViewPosition;

varying vec3 vNormal;
varying vec3 vViewVec;
varying vec2 vTexCoord0;

void main(void) {
    gl_Position = uPMatrix * uMVMatrix * vec4(aVertex, 1.0);

    vNormal = aNormal;
    vViewVec = uViewPosition.xyz - aVertex.xyz;
    vTexCoord0 = aTexCoord0;
}
</script>

<script id="shader-fs" type="x-shader/x-fragment">
varying vec3 vNormal;
varying vec3 vViewVec;
varying vec2 vTexCoord0;

uniform vec4 uColor;
uniform sampler2D uTexture0;

void main(void) {
    float v = 0.5 * (1.0 + dot(normalize(vViewVec), vNormal));
    
    gl_FragColor = texture2D(uTexture0, vTexCoord0.st);
}
</script>

<script type="text/javascript">

  // our global context reference; we only have one canvas and one context,
  // so we don't have to keep passing this around
  var gl;

  // we'll read the width and height from the canvas object
  var canvasWidth = 0;
  var canvasHeight = 0;



  var shaders = {};
  var shadersParams = {};
  var img;
  var currentRotation=0;
  var pmMatrix;
  var texid;
  function init()
  {
  // Grab the canvas object and its dimensions
  var canvas = document.getElementById("c");
  canvasWidth = canvas.width;
  canvasHeight = canvas.height;

  // Request a moz-glweb20 rendering context from the canvas, and
  // store it in the gl global
  gl = canvas.getContext("moz-webgl");
  if (!gl)
  {
  // failed to get the context
  alert("Can't find a WebGL context; is it enabled?");
  return false;
  }

  if (!("sp" in shaders))
  {
  shaders.fs = getShader(gl, "shader-fs");
  shaders.vs = getShader(gl, "shader-vs");

  shaders.sp = gl.createProgram();
  gl.attachShader(shaders.sp, shaders.vs);
  gl.attachShader(shaders.sp, shaders.fs);
  gl.linkProgram(shaders.sp);

  if (!gl.getProgrami(shaders.sp, gl.LINK_STATUS))
  {
  alert(gl.getProgramInfoLog(shader));
  }
  gl.useProgram(shaders.sp);
  }
  // set up the clear color to clear to transparent black
  gl.clearColor (0, 0, 0, 1);

  // Get all param of shaders
  var sp = shaders.sp;

  shadersParams.va = gl.getAttribLocation(sp, "aVertex");
  shadersParams.na = gl.getAttribLocation(sp, "aNormal");
  shadersParams.ta = gl.getAttribLocation(sp, "aTexCoord0");

  shadersParams.modelviewM    = gl.getUniformLocation(sp, "uMVMatrix");
  shadersParams.projectM      = gl.getUniformLocation(sp, "uPMatrix");
  shadersParams.texture0      = gl.getUniformLocation(sp, "uTexture0");

  shadersParams.viewPosition  = gl.getUniformLocation(sp, "uViewPosition");
  //shadersParams.colorUniform  = gl.getUniformLocation(sp, "uColor");
  //gl.uniform4fv(colorUniform, new CanvasFloatArray([0.1, 0.2, 0.4, 1.0]));

  // Load texture
  img = new Image();
  img.onLoad = function(){
      alert("LOADED!");
  }
  img.src = "Resource/cubeTex.jpg";

  var mouseDown = false;
  var lastX = 0;
  mvMatrix = makeLookAt(5,5,5,
  0,0,0,
  0,1,1);

  pmMatrix = makePerspective(60, 1, 0.1, 100);
  // Event handle
  canvas.addEventListener("mousedown", function(ev) {
  mouseDown = true;
  lastX = ev.screenX;
  return true;
  }, false);

  canvas.addEventListener("mousemove", function(ev) {

  if (!mouseDown)
  return false;
  var mdelta = ev.screenX - lastX;
  lastX = ev.screenX;
  currentRotation -= mdelta;
  while (currentRotation < 0)
                              currentRotation += 360;
                            if (currentRotation >= 360)
                              currentRotation = currentRotation % 360;
  
                            draw();
                            return true;
                          }, false);

  canvas.addEventListener("mouseup", function(ev) {
                            mouseDown = false;
                          }, false);
                          
    
        
    return true;
}
function setMatrixUniforms(mvMatrix,pmMatrix,vpos) 
{
    gl.uniformMatrix4fv(shadersParams.modelviewM, false, mvMatrix.data);
    gl.uniformMatrix4fv(shadersParams.projectM, false, pmMatrix.data);
    gl.uniform3fv(shadersParams.viewPosition, new WebGLFloatArray(vpos));
}
  var mvMatrixStack = [];
  var mvMatrix = new gewMat4();
  
function multMatrix(m) {
    //console.log("mult", m.flatten());
    mvMatrix = mvMatrix.mul(m);
  }

 function mvTranslate(v) {
    var m = Mat4.getTranslate(v);
    multMatrix(m);
  }

  function mvRotate(ang, v) {
    var arad = ang * Math.PI / 180.0;
    var m = gewMat4.getRotate(v,arad);
    multMatrix(m);
  }
  
// Actually draw the triangle, using the program created in init()
var vertices = [ 1,-1,-1,
                 -1,-1,-1,
                  1,-1, 1,
                 -1,-1, 1,
                 -1, 1, 1,
                 -1, 1,-1,
                 -1,-1,-1,
                 1, 1,-1,
                 1,-1,-1,
                 1, 1, 1,
                 1,-1, 1,
                 -1, 1, 1,
                 -1, 1,-1]; 
var tex_uis = [ 0,0,
                0,1,
                1,0,
                1,1,
                0,0,
                1,0,
                0,1,
                1,1,
                0,0,
                1,0,
                0,1,
                1,1,
                0,0];
function pushMatrix(m) {
if (m) {
      mvMatrixStack.push(m.dup());
      mvMatrix = m.dup();
    } else {
      mvMatrixStack.push(mvMatrix.dup());
    }
  }

  function popMatrix() {
    if (mvMatrixStack.length == 0)
      throw "Invalid popMatrix!";
    mvMatrix = mvMatrixStack.pop();
    return mvMatrix;
  }
  var texturesBound = false;
function draw()
{
    pushMatrix();

   mvRotate(currentRotation, new gewVec3(0,0,1) );
    // Calc modelview matrix

    var vPos = [5,5,5];
    setMatrixUniforms(mvMatrix,pmMatrix,vPos);       
    
    // Set up texture
    if (!texturesBound) 
    {
      if (img.complete) 
      {
        texid = gl.createTexture();
        gl.activeTexture(gl.TEXTURE0);
        gl.bindTexture(gl.TEXTURE_2D, texid);
        // XXX we should be able to just pass TRUE to flipY for texImage2D here,
        // but we don't support that yet
        gl.texImage2D(gl.TEXTURE_2D, 0, img);
        gl.generateMipmap(gl.TEXTURE_2D);
        if (img.width > 0 && img.height > 0)
    {
    // the texture is ready for binding

    gl.uniform1i(shadersParams.texture0, texid);

    // gl.enable(gl.TEXTURING);
    // gl.enable(gl.TEXTURE_2D);
    }
    texturesBound = true;
    }
    }

    // Set up the viewport
    gl.viewport(0, 0, canvasWidth, canvasHeight);

    // Clear the color buffer
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    // set up the vbos
    var buffers = { };
    buffers.position = gl.createBuffer();
    buffers.tex_ui = gl.createBuffer();

    gl.enable(gl.DEPTH_TEST);
    gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
    gl.bufferData(gl.ARRAY_BUFFER, new WebGLFloatArray(vertices), gl.STATIC_DRAW);
    gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
    // Load the vertex data
    // XXX we seem to have lost the |normalized| and |stride| params!
    gl.vertexAttribPointer(shadersParams.va, 3, gl.FLOAT, false, 0, 0);
    gl.enableVertexAttribArray(shadersParams.va);


    gl.bindBuffer(gl.ARRAY_BUFFER, buffers.tex_ui);
    gl.bufferData(gl.ARRAY_BUFFER, new WebGLFloatArray(tex_uis), gl.STATIC_DRAW);
    gl.bindBuffer(gl.ARRAY_BUFFER, buffers.tex_ui);

    gl.vertexAttribPointer(shadersParams.ta, 2, gl.FLOAT, false, 0, 0);
    gl.enableVertexAttribArray(shadersParams.ta);


    // Do the draw, as triangles
    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 13);

    // Finally do the swap to display what we just drew
    //gl.swapBuffers();
    popMatrix();
    }

    function main()
    {
    if (!init())
    return;

    // our scene is static, so we only need to draw once
    draw()
  }

    // Use jQuery to get a callback for when the page has loaded and we can interact
    // with it; the same could be accomplished with an explicit event listener for
    // the load event.
    //$(document).ready(main);

  </script>

<style type="text/css">
canvas {
  border: 1px solid gray;
}
</style>
</head>

<body onload="main()">
  <div style="text-align: center">
    <!-- this is the canvas that we render to -->
    <canvas id="c" width="640" height="480"></canvas>

    <!-- a convenient div to use to display log messages -->
    <a>Dont see anything? Get FireFox 3.7 and enable webGL feature ( about:config >> set webGL.. param to true )</a>
  </div>
</body>
</html>
